package repository

import (
	"context"
	"database/sql"
	"encoding/json"
	"fmt"
	"strconv"
	"strings"
	"time"

	"mall/common/globalkey"
	"mall/common/modelx"
	"mall/service/product/model"

	"github.com/sirupsen/logrus"
	"github.com/volatiletech/null/v8"
	"github.com/volatiletech/sqlboiler/v4/boil"
	"github.com/volatiletech/sqlboiler/v4/queries/qm"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/core/stores/cache"
)

type (
	// CurrentProductTermRepository is an interface to be customized, add more methods here,
	// and implement the added methods in customCurrentProductTermRepository.
	CurrentProductTermRepository interface {
		FindOne(ctx context.Context, id uint64) (*model.ProductTerm, error)
		FindOneWithExpire(
			ctx context.Context,
			id uint64,
			expire time.Duration,
		) (*model.ProductTerm, error)
		FindOneNoCache(
			ctx context.Context,
			conn boil.ContextExecutor,
			id uint64,
		) (*model.ProductTerm, error)
		GetList(
			ctx context.Context,
			cols model.M,
			withCount int,
			filter map[string]map[string][]any,
		) ([]*model.ProductTerm, int64, error) // ##24.12.17##
		Insert(
			ctx context.Context,
			tx boil.ContextExecutor,
			data *model.ProductTerm,
			rel *model.ProductTermRel,
		) error // ##25.01.26##
		Update(
			ctx context.Context,
			tx boil.ContextExecutor,
			data *model.ProductTerm,
			rel *model.ProductTermRel,
		) error // #24.08.13#
		UpdateBatch(ctx context.Context, tx boil.ContextExecutor, ids []uint64, cols model.M) error
		SoftDelete(ctx context.Context, tx boil.ContextExecutor, id uint64) error // ##25.01.31##
		Restore(ctx context.Context, tx boil.ContextExecutor, id uint64) error    // ##25.01.31##
		ForceDelete(ctx context.Context, tx boil.ContextExecutor, id uint64) error
		ForceDeleteBatch(ctx context.Context, tx boil.ContextExecutor, ids []uint64) error

		SyncQiniu(ctx context.Context, id uint64, mediaId uint64, url string) (int64, error) // ##25.02.18##

		GetMeta(
			ctx context.Context,
			cols model.M,
			withCount int,
			filter map[string]map[string][]any,
		) ([]*model.ProductTermMetum, int64, error)
		GetMedia(
			ctx context.Context,
			cols model.M,
			withCount int,
			filter map[string]map[string][]any,
		) ([]*model.ProductAttachmentRelationship, int64, error)
		GetRelationshipList(
			ctx context.Context,
			cols model.M,
			withCount int,
			filter map[string]map[string][]any,
		) ([]*model.ProductTermRelationship, int64, error) // ##24.12.17##
	}

	customCurrentProductTermRepository struct {
		modelx.CachedConn
		mysqlConn           *sql.DB
		cacheIdPrefix       string
		cacheIdExpirePrefix string
	}
)

// NewCurrentProductTermRepository returns a repository for the database table.
func NewCurrentProductTermRepository(mysqlConn *sql.DB, cacheConf cache.CacheConf) CurrentProductTermRepository {
	return &customCurrentProductTermRepository{
		CachedConn:          modelx.NewConn(mysqlConn, cacheConf),
		mysqlConn:           mysqlConn,
		cacheIdPrefix:       "cache:product:product_terms:id:",
		cacheIdExpirePrefix: "cache:product:product_terms:id:expire:",
	}
}

func (r *customCurrentProductTermRepository) FindOne(
	ctx context.Context,
	id uint64,
) (*model.ProductTerm, error) {
	cacheIdKey := r.formatPrimary(id)
	var resp model.ProductTerm
	err := r.QueryCtx(ctx, &resp, cacheIdKey, func(ctx context.Context, conn *sql.DB, v any) error {
		data, err := model.FindProductTerm(ctx, conn, id)
		if err != nil {
			return err
		}

		*v.(*model.ProductTerm) = *data

		return nil
	})

	switch err {
	case nil:
		return &resp, nil
	case sql.ErrNoRows:
		return nil, model.ErrNotFound
	default:
		return nil, err
	}
}

func (r *customCurrentProductTermRepository) FindOneWithExpire(
	ctx context.Context,
	id uint64,
	expire time.Duration,
) (*model.ProductTerm, error) {
	cacheIdKey := r.formatPrimary(id)
	var resp model.ProductTerm
	err := r.QueryWithExpireCtx(ctx, &resp, cacheIdKey, expire, func(ctx context.Context, conn *sql.DB, v any) error {
		data, err := model.FindProductTerm(ctx, conn, id)
		if err != nil {
			return err
		}

		*v.(*model.ProductTerm) = *data

		return nil
	})

	switch err {
	case nil:
		return &resp, nil
	case sql.ErrNoRows:
		return nil, model.ErrNotFound
	default:
		return nil, err
	}
}

func (r *customCurrentProductTermRepository) FindOneNoCache(
	ctx context.Context,
	conn boil.ContextExecutor,
	id uint64,
) (*model.ProductTerm, error) {
	var db boil.ContextExecutor = r.mysqlConn
	if conn != nil {
		db = conn
	}
	data, err := model.FindProductTerm(ctx, db, id)
	switch err {
	case nil:
		return data, nil
	case sql.ErrNoRows:
		return nil, model.ErrNotFound
	default:
		return nil, err
	}
}

func (r *customCurrentProductTermRepository) GetList(
	ctx context.Context,
	cols model.M,
	withCount int,
	filter map[string]map[string][]any,
) (list []*model.ProductTerm, count int64, err error) {
	var page int
	var pageSize int
	var limit int
	var selectCol string
	var mods []qm.QueryMod
	var nextCount int64
	var previousCount int64
	var statistic bool
	for k, v := range cols {
		switch k {
		case "page":
			if val, ok := v.(uint64); ok && val > 1 {
				page = int(val)
			}
		case "pageSize":
			if val, ok := v.(uint64); ok && val > 0 {
				pageSize = int(val)
			}
		case "limit":
			if val, ok := v.(uint32); ok && val > 0 {
				limit = int(val)
			}
		case "offset":
			if withCount == 2 {
				if val, ok := v.(uint32); ok && val > 0 {
					mods = append(mods, qm.Offset(int(val)))
					previousCount = 1
				}
			}
		case "orderBy":
			if val, ok := v.(string); ok && len(val) > 0 {
				mods = append(mods, qm.OrderBy(val))
			}
		case "preMinId":
			if withCount == 3 {
				if val, ok := v.(uint64); ok && val > 0 {
					mods = append(mods, qm.OrderBy(model.ProductTermColumns.TermID+" DESC"))
					mods = append(mods, model.ProductTermWhere.TermID.LT(val))
					previousCount = 1
				}
			}
		case "preMaxId":
			if withCount == 4 {
				if val, ok := v.(uint64); ok && val > 0 {
					mods = append(mods, qm.OrderBy(model.ProductTermColumns.TermID+" ASC"))
					mods = append(mods, model.ProductTermWhere.TermID.GT(val))
					previousCount = 1
				}
			}
		case "select":
			if withCount != 5 {
				if val, ok := v.(string); ok && len(val) > 0 {
					selectCol = val
				}
			}
		case "search":
			if val, ok := v.(string); ok && len(val) > 0 { // 搜索
				likeVal := fmt.Sprintf("%%%s%%", val)
				mods = append(mods, qm.Where(fmt.Sprintf(
					"(%s LIKE ? OR %s LIKE ?)",
					model.ProductTermColumns.Name,
					model.ProductTermColumns.Slug), likeVal, likeVal))
			}
		case "statistic":
			if val, ok := v.(string); ok && val == "1" { // 按 Status 统计
				statistic = true
			}
		}
	}

	for key, opMap := range filter {
		switch key {
		case model.ProductTermColumns.TermID:
			mods = append(mods, modelx.GetIntMods(model.ProductTermColumns.TermID, opMap)...)
		case model.ProductTermColumns.Name:
			mods = append(mods, modelx.GetStringMods(model.ProductTermColumns.Name, opMap)...)
		case model.ProductTermColumns.Slug:
			mods = append(mods, modelx.GetStringMods(model.ProductTermColumns.Slug, opMap)...)
		case model.ProductTermColumns.Taxonomy:
			mods = append(mods, modelx.GetIntMods(model.ProductTermColumns.Taxonomy, opMap)...)
		case model.ProductTermColumns.ParentID:
			mods = append(mods, modelx.GetIntMods(model.ProductTermColumns.ParentID, opMap)...)
		case model.ProductTermColumns.TermGroup:
			mods = append(mods, modelx.GetIntMods(model.ProductTermColumns.TermGroup, opMap)...)
		case model.ProductTermColumns.Count:
			mods = append(mods, modelx.GetIntMods(model.ProductTermColumns.Count, opMap)...)
		case model.ProductTermColumns.Status:
			mods = append(mods, modelx.GetIntMods(model.ProductTermColumns.Status, opMap)...)
		case model.ProductTermColumns.CreatedAt:
			mods = append(mods, modelx.GetTimeMods(model.ProductTermColumns.CreatedAt, opMap)...)
		case model.ProductTermColumns.UpdatedAt:
			mods = append(mods, modelx.GetTimeMods(model.ProductTermColumns.UpdatedAt, opMap)...)
		case model.ProductTermColumns.DeletedAt:
			mods = append(mods, modelx.GetTimeMods(model.ProductTermColumns.DeletedAt, opMap)...)
		}
	}

	if statistic {
		mods = append(mods, qm.Select(fmt.Sprintf(
			"%s, count(%s) as %s",
			model.ProductTermColumns.Status,
			model.ProductTermColumns.Status,
			model.ProductTermColumns.Count,
		)))
		mods = append(mods, qm.GroupBy(model.ProductTermColumns.Status))
		preList, preErr := model.ProductTerms(mods...).All(ctx, r.mysqlConn)
		if preErr != nil {
			err = preErr
			return
		}

		return preList, 0, nil
	}

	if withCount >= 2 {
		if limit > 0 {
			mods = append(mods, qm.Limit(limit+1))
		}
	} else if withCount >= 0 {
		count, err = model.ProductTerms(mods...).Count(ctx, r.mysqlConn)
		if err != nil {
			return
		}

		if withCount == 0 {
			return
		}
	}

	if pageSize > 0 && (withCount == -1 || withCount == 1) {
		if page > 1 {
			mods = append(mods, qm.Offset(pageSize*(page-1)))
		}
		mods = append(mods, qm.Limit(pageSize))
	}

	var columns []string
	if len(selectCol) > 0 {
		if selectCol == "," {
			columns = append(columns, model.ProductTermColumns.TermID)
		} else {
			columns = strings.Split(selectCol, ",")
		}
	}
	if len(columns) > 0 {
		mods = append(mods, qm.Select(columns...))
	}

	list, err = model.ProductTerms(mods...).All(ctx, r.mysqlConn)
	if err != nil {
		return
	}

	if withCount >= 2 {
		if limit > 0 && len(list) > limit {
			nextCount = 1
			list = list[:limit]
		}
		count = previousCount + nextCount*2
	}

	return
}

func (r *customCurrentProductTermRepository) Insert(
	ctx context.Context,
	tx boil.ContextExecutor,
	data *model.ProductTerm,
	rel *model.ProductTermRel,
) error {
	err := r.ExecCtx(ctx, func(ctx context.Context, conn *sql.DB) error {
		var db boil.ContextExecutor
		if tx != nil {
			db = tx
		} else {
			db = conn
		}

		err := data.Insert(ctx, db, boil.Infer())
		if err != nil {
			return err
		}

		if rel == nil {
			return nil
		}

		tid := data.TermID
		if len(rel.Meta) > 0 {
			for _, v := range rel.Meta {
				v.TermID = tid
				err = v.Insert(ctx, db, boil.Infer())
				if err != nil {
					return err
				}
			}
		}

		if len(rel.Media) > 0 {
			for _, v := range rel.Media {
				v.ObjectID = tid
				v.ObjectType = data.Taxonomy + globalkey.AttachmentLogTypeTermOffset
				err = v.Insert(ctx, db, boil.Infer())
				if err != nil {
					return err
				}
			}
		}

		return nil
	}, r.getCacheKeys(data)...)

	return err
}

func (r *customCurrentProductTermRepository) Update(
	ctx context.Context,
	tx boil.ContextExecutor,
	data *model.ProductTerm,
	rel *model.ProductTermRel,
) error {
	err := r.ExecCtx(ctx, func(ctx context.Context, conn *sql.DB) error {
		var db boil.ContextExecutor
		if tx != nil {
			db = tx
		} else {
			db = conn
		}

		rowsAff, err := data.Update(ctx, db, boil.Blacklist(
			model.ProductTermColumns.TermID,
			model.ProductTermColumns.DeletedAt,
		))
		if err != nil {
			return err
		}

		if rowsAff == 0 {
			return model.ErrNotUpdated
		}

		if rel == nil {
			return nil
		}

		tid := data.TermID

		if len(rel.Meta) > 0 {
			for _, v := range rel.Meta {
				if v.MetaID > 0 {
					_, err = v.Update(ctx, db, boil.Blacklist(
						model.ProductTermMetumColumns.MetaID,
						model.ProductTermMetumColumns.TermID,
						model.ProductTermMetumColumns.MetaKey,
					))
				} else {
					v.TermID = tid
					err = v.Insert(ctx, db, boil.Infer())
				}
				if err != nil {
					return err
				}
			}
		}

		if len(rel.Media) > 0 {
			for _, v := range rel.Media {
				if v.AttachmentRelationshipID > 0 {
					_, err = v.Update(ctx, db, boil.Blacklist(
						model.ProductAttachmentRelationshipColumns.AttachmentRelationshipID,
						model.ProductAttachmentRelationshipColumns.ObjectID,
						model.ProductAttachmentRelationshipColumns.ObjectType,
						model.ProductAttachmentRelationshipColumns.AttachmentID,
					))
				} else {
					v.ObjectID = tid
					v.ObjectType = data.Taxonomy + globalkey.AttachmentLogTypeTermOffset
					err = v.Insert(ctx, db, boil.Infer())
				}
				if err != nil {
					return err
				}
			}
		}

		if len(rel.DelMetaIds) > 0 {
			var mods []qm.QueryMod
			mods = append(mods, model.ProductTermMetumWhere.MetaID.IN(rel.DelMetaIds))
			_, err = model.ProductTermMeta(mods...).DeleteAll(ctx, db)
			if err != nil {
				return err
			}
		}
		if len(rel.DelMediaIds) > 0 {
			var mods []qm.QueryMod
			mods = append(mods, model.ProductAttachmentRelationshipWhere.AttachmentRelationshipID.IN(rel.DelMediaIds))
			_, err = model.ProductAttachmentRelationships(mods...).DeleteAll(ctx, db)
			if err != nil {
				return err
			}
		}

		return nil
	}, r.getCacheKeys(data)...)

	return err
}

func (r *customCurrentProductTermRepository) UpdateBatch(
	ctx context.Context,
	tx boil.ContextExecutor,
	ids []uint64,
	cols model.M,
) error {
	if len(ids) > 0 {
		err := r.ExecCtx(ctx, func(ctx context.Context, conn *sql.DB) error {
			var db boil.ContextExecutor
			if tx != nil {
				db = tx
			} else {
				db = conn
			}

			var mods []qm.QueryMod
			mods = append(mods, model.ProductTermWhere.TermID.IN(ids))

			rowsAff, err := model.ProductTerms(mods...).UpdateAll(ctx, db, cols)
			if err != nil {
				return err
			}

			if rowsAff == 0 {
				return model.ErrNotUpdated
			}

			return nil
		}, r.formatPrimaries(ids)...)

		return err
	}

	return nil
}

func (r *customCurrentProductTermRepository) SoftDelete(
	ctx context.Context,
	tx boil.ContextExecutor,
	id uint64,
) error {
	data, err := r.FindOneNoCache(ctx, tx, id)
	if err != nil {
		if err == model.ErrNotFound {
			return nil
		}

		return err
	}

	if data.Status == uint8(globalkey.StatusDeleted) {
		return nil
	}

	data.DelStatus = data.Status
	data.Status = uint8(globalkey.StatusDeleted)
	data.DeletedAt = null.TimeFrom(time.Now())

	err = r.ExecCtx(ctx, func(ctx context.Context, conn *sql.DB) error {
		var db boil.ContextExecutor
		if tx != nil {
			db = tx
		} else {
			db = conn
		}

		rowsAff, err := data.Update(ctx, db, boil.Whitelist(
			model.ProductTermColumns.DelStatus,
			model.ProductTermColumns.Status,
			model.ProductTermColumns.DeletedAt,
		))
		if err != nil {
			return err
		}

		if rowsAff == 0 {
			return model.ErrNotUpdated
		}

		return nil
	}, r.getCacheKeys(data)...)

	return err
}

func (r *customCurrentProductTermRepository) Restore(
	ctx context.Context,
	tx boil.ContextExecutor,
	id uint64,
) error {
	data, err := r.FindOneNoCache(ctx, tx, id)
	if err != nil {
		if err == model.ErrNotFound {
			return nil
		}

		return err
	}

	if data.Status != uint8(globalkey.StatusDeleted) {
		return nil
	}

	data.Status = data.DelStatus
	data.DeletedAt = null.TimeFromPtr(nil)

	err = r.ExecCtx(ctx, func(ctx context.Context, conn *sql.DB) error {
		var db boil.ContextExecutor
		if tx != nil {
			db = tx
		} else {
			db = conn
		}

		rowsAff, err := data.Update(ctx, db, boil.Whitelist(
			model.ProductTermColumns.Status,
			model.ProductTermColumns.DeletedAt,
		))
		if err != nil {
			return err
		}

		if rowsAff == 0 {
			return model.ErrNotUpdated
		}

		return nil
	}, r.getCacheKeys(data)...)

	return err
}

func (r *customCurrentProductTermRepository) ForceDelete(
	ctx context.Context,
	tx boil.ContextExecutor,
	id uint64,
) error {
	data, err := r.FindOneNoCache(ctx, tx, id)
	if err != nil {
		if err == model.ErrNotFound {
			return nil
		}

		return err
	}

	err = r.ExecCtx(ctx, func(ctx context.Context, conn *sql.DB) error {
		var db boil.ContextExecutor
		if tx != nil {
			db = tx
		} else {
			db = conn
		}

		rowsAff, err := data.Delete(ctx, db)
		if err != nil {
			return err
		}

		if rowsAff == 0 {
			return model.ErrNotDeleted
		}

		return nil
	}, r.getCacheKeys(data)...)

	return err
}

func (r *customCurrentProductTermRepository) ForceDeleteBatch(
	ctx context.Context,
	tx boil.ContextExecutor,
	ids []uint64,
) error {
	if len(ids) > 0 {
		err := r.ExecCtx(ctx, func(ctx context.Context, conn *sql.DB) error {
			var db boil.ContextExecutor
			if tx != nil {
				db = tx
			} else {
				db = conn
			}

			var mods []qm.QueryMod
			mods = append(mods, model.ProductTermWhere.TermID.IN(ids))

			rowsAff, err := model.ProductTerms(mods...).DeleteAll(ctx, db)
			if err != nil {
				return err
			}

			if rowsAff == 0 {
				return model.ErrNotDeleted
			}

			return nil
		}, r.formatPrimaries(ids)...)

		return err
	}

	return nil
}

func (r *customCurrentProductTermRepository) SyncQiniu(ctx context.Context, id uint64, mediaId uint64, url string) (rowsAff int64, err error) {
	var mods []qm.QueryMod
	mods = append(mods, model.ProductAttachmentRelationshipWhere.ObjectID.EQ(id))
	mods = append(mods, model.ProductAttachmentRelationshipWhere.AttachmentID.EQ(mediaId))
	list, err := model.ProductAttachmentRelationships(mods...).All(ctx, r.mysqlConn)
	if err != nil {
		return
	}

	if len(list) == 0 {
		return
	}

	urlStr := url + "?" + strconv.FormatUint(mediaId, 10)

	for _, item := range list {
		if len(item.AttachmentSource) == 0 {
			continue
		}

		var subMods []qm.QueryMod
		var metaMods []qm.QueryMod
		switch int32(item.ObjectType) {
		case globalkey.AttachmentLogTypeProduct:
			subMods = append(subMods, model.ProductDetailWhere.ProductID.EQ(item.ObjectID))
			subList, err := model.ProductDetails(subMods...).All(ctx, r.mysqlConn)
			if err != nil {
				logx.Errorw("SyncQiniu ProductDetail error", logx.Field("detail", err.Error()))
				logrus.Info(fmt.Sprintf("SyncQiniu ProductDetail error, productId: %d, err: %+v", item.ObjectID, err))
				continue
			}

			for _, subItem := range subList {
				subItem.Content = strings.Replace(subItem.Content, item.AttachmentSource, urlStr, -1)
				subItem.ContentFiltered = strings.Replace(subItem.ContentFiltered, item.AttachmentSource, urlStr, -1)
				if subItem.Tracing.Valid {
					subItem.Tracing = null.StringFrom(strings.Replace(subItem.Tracing.String, item.AttachmentSource, urlStr, -1))
				}
				if subItem.TracingFiltered.Valid {
					subItem.TracingFiltered = null.StringFrom(strings.Replace(subItem.TracingFiltered.String, item.AttachmentSource, urlStr, -1))
				}
				_, err = subItem.Update(ctx, r.mysqlConn, boil.Blacklist(
					model.ProductDetailColumns.DetailID,
					model.ProductDetailColumns.ProductID,
				))
				if err != nil {
					logx.Errorw("SyncQiniu ProductDetail update error", logx.Field("detail", err.Error()))
					logrus.Info(fmt.Sprintf("SyncQiniu ProductDetail update error, productId: %d, err: %+v", item.ObjectID, err))
				}
			}

			if item.AttachmentThumbnail == 0 || item.AttachmentOrder > 0 {
				continue
			}

			metaMods = append(metaMods, model.ProductMetumWhere.ProductID.EQ(item.ObjectID))
			metaMods = append(metaMods, model.ProductMetumWhere.MetaKey.EQ("_thumbnail_url"))
			metaList, err := model.ProductMeta(metaMods...).All(ctx, r.mysqlConn)
			if err != nil {
				logx.Errorw("SyncQiniu ProductMeta error", logx.Field("detail", err.Error()))
				logrus.Info(fmt.Sprintf("SyncQiniu ProductMeta error, productId: %d, err: %+v", item.ObjectID, err))
				continue
			}

			for _, metum := range metaList {
				metum.MetaValue = null.StringFrom(url)
				_, err = metum.Update(ctx, r.mysqlConn, boil.Whitelist(
					model.ProductMetumColumns.MetaValue,
				))
				if err != nil {
					logx.Errorw("SyncQiniu ProductMeta update error", logx.Field("detail", err.Error()))
					logrus.Info(fmt.Sprintf("SyncQiniu ProductMeta update error, productId: %d, err: %+v", item.ObjectID, err))
				}
			}
		case globalkey.AttachmentLogTypeProductTerm:
			subMods = append(subMods, model.ProductTermWhere.TermID.EQ(item.ObjectID))
			subList, subErr := model.ProductTerms(subMods...).All(ctx, r.mysqlConn)
			if subErr != nil {
				logx.Errorw("SyncQiniu ProductTerm error", logx.Field("detail", subErr.Error()))
				logrus.Info(fmt.Sprintf("SyncQiniu ProductTerm error, termId: %d, err: %+v", item.ObjectID, subErr))
				continue
			}

			for _, subItem := range subList {
				subItem.Description = strings.Replace(subItem.Description, item.AttachmentSource, urlStr, -1)
				subItem.DescriptionFiltered = strings.Replace(subItem.DescriptionFiltered, item.AttachmentSource, urlStr, -1)
				_, subErr = subItem.Update(ctx, r.mysqlConn, boil.Blacklist(
					model.ProductTermColumns.TermID,
					model.ProductTermColumns.UpdatedAt,
				))
				if subErr != nil {
					logx.Errorw("SyncQiniu ProductTerm update error", logx.Field("detail", subErr.Error()))
					logrus.Info(fmt.Sprintf("SyncQiniu ProductTerm update error, termId: %d, err: %+v", item.ObjectID, subErr))
				}
			}

			if item.AttachmentThumbnail == 0 || item.AttachmentOrder > 0 {
				continue
			}

			metaMods = append(metaMods, model.ProductTermMetumWhere.TermID.EQ(item.ObjectID))
			metaMods = append(metaMods, model.ProductTermMetumWhere.MetaKey.EQ("_thumbnail_url"))
			metaList, err := model.ProductTermMeta(metaMods...).All(ctx, r.mysqlConn)
			if err != nil {
				logx.Errorw("SyncQiniu ProductTermMeta error", logx.Field("detail", err.Error()))
				logrus.Info(fmt.Sprintf("SyncQiniu ProductTermMeta error, termId: %d, err: %+v", item.ObjectID, err))
				continue
			}

			for _, metum := range metaList {
				metum.MetaValue = null.StringFrom(url)
				_, err = metum.Update(ctx, r.mysqlConn, boil.Whitelist(
					model.ProductTermMetumColumns.MetaValue,
				))
				if err != nil {
					logx.Errorw("SyncQiniu ProductTermMeta update error", logx.Field("detail", err.Error()))
					logrus.Info(fmt.Sprintf("SyncQiniu ProductTermMeta update error, productId: %d, err: %+v", item.ObjectID, err))
				}
			}
		}
	}

	rowsAff, err = model.ProductAttachmentRelationships(mods...).UpdateAll(ctx, r.mysqlConn, model.M{
		model.ProductAttachmentRelationshipColumns.AttachmentImageURL: url,
	})

	return
}

func (r *customCurrentProductTermRepository) getCacheKeys(data *model.ProductTerm) []string {
	if data == nil {
		return []string{}
	}

	cacheIdKey := r.formatPrimary(data.TermID)
	cacheIdExpireKey := r.formatPrimaryWithExpire(data.TermID)
	cacheKeys := []string{
		cacheIdKey,
		cacheIdExpireKey,
	}

	return cacheKeys
}

func (r *customCurrentProductTermRepository) formatPrimary(primary any) string {
	return fmt.Sprintf("%s%v", r.cacheIdPrefix, primary)
}

func (r *customCurrentProductTermRepository) formatPrimaryWithExpire(primary any) string {
	return fmt.Sprintf("%s%v", r.cacheIdExpirePrefix, primary)
}

func (r *customCurrentProductTermRepository) formatPrimaries(primaries []uint64) []string {
	var resp []string
	for _, primary := range primaries {
		resp = append(resp, r.formatPrimary(primary))
		resp = append(resp, r.formatPrimaryWithExpire(primary))
	}

	return resp
}

func (r *customCurrentProductTermRepository) queryPrimary(ctx context.Context, conn *sql.DB, v, primary any) error {
	var tid uint64
	if jsonId, ok := primary.(json.Number); ok {
		if int64Id, err := jsonId.Int64(); err == nil {
			tid = uint64(int64Id)
		} else {
			return err
		}
	}

	data, err := model.FindProductTerm(ctx, conn, tid)
	if err != nil {
		return err
	}

	*v.(*model.ProductTerm) = *data

	return nil
}

func (r *customCurrentProductTermRepository) GetMeta(
	ctx context.Context,
	cols model.M,
	withCount int,
	filter map[string]map[string][]any,
) (list []*model.ProductTermMetum, count int64, err error) {
	var page int
	var pageSize int
	var limit int
	var selectCol string
	var mods []qm.QueryMod
	var nextCount int64
	var previousCount int64
	for k, v := range cols {
		switch k {
		case "page":
			if val, ok := v.(uint64); ok && val > 1 {
				page = int(val)
			}
		case "pageSize":
			if val, ok := v.(uint64); ok && val > 0 {
				pageSize = int(val)
			}
		case "limit":
			if val, ok := v.(uint32); ok && val > 0 {
				limit = int(val)
			}
		case "offset":
			if withCount == 2 {
				if val, ok := v.(uint32); ok && val > 0 {
					mods = append(mods, qm.Offset(int(val)))
					previousCount = 1
				}
			}
		case "orderBy":
			if val, ok := v.(string); ok && len(val) > 0 {
				mods = append(mods, qm.OrderBy(val))
			}
		case "preMinId":
			if withCount == 3 {
				if val, ok := v.(uint64); ok && val > 0 {
					mods = append(mods, qm.OrderBy(model.ProductTermMetumColumns.MetaID+" DESC"))
					mods = append(mods, model.ProductTermMetumWhere.MetaID.LT(val))
					previousCount = 1
				}
			}
		case "preMaxId":
			if withCount == 4 {
				if val, ok := v.(uint64); ok && val > 0 {
					mods = append(mods, qm.OrderBy(model.ProductTermMetumColumns.MetaID+" ASC"))
					mods = append(mods, model.ProductTermMetumWhere.MetaID.GT(val))
					previousCount = 1
				}
			}
		case "select":
			if val, ok := v.(string); ok && len(val) > 0 {
				selectCol = val
			}
		}
	}

	for key, opMap := range filter {
		switch key {
		case model.ProductTermMetumColumns.MetaID:
			mods = append(mods, modelx.GetIntMods(model.ProductTermMetumColumns.MetaID, opMap)...)
		case model.ProductTermMetumColumns.TermID:
			mods = append(mods, modelx.GetIntMods(model.ProductTermMetumColumns.TermID, opMap)...)
		case model.ProductTermMetumColumns.MetaKey:
			mods = append(mods, modelx.GetStringMods(model.ProductTermMetumColumns.MetaKey, opMap)...)
		case model.ProductTermMetumColumns.MetaValue:
			mods = append(mods, modelx.GetStringMods(model.ProductTermMetumColumns.MetaValue, opMap)...)
		}
	}

	if withCount >= 2 {
		if limit > 0 {
			mods = append(mods, qm.Limit(limit+1))
		}
	} else if withCount >= 0 {
		count, err = model.ProductTermMeta(mods...).Count(ctx, r.mysqlConn)
		if err != nil {
			return
		}

		if withCount == 0 {
			return
		}

		if pageSize > 0 {
			if page > 1 {
				mods = append(mods, qm.Offset(pageSize*(page-1)))
			}
			mods = append(mods, qm.Limit(pageSize))
		}
	} else {
		if pageSize > 0 {
			if page > 1 {
				mods = append(mods, qm.Offset(pageSize*(page-1)))
			}
			mods = append(mods, qm.Limit(pageSize))
		}
	}

	var columns []string
	if selectCol != "" {
		if selectCol != "," {
			columns = strings.Split(selectCol, ",")
		} else {
			columns = append(columns, model.ProductTermMetumColumns.MetaID)
		}
	}
	if len(columns) > 0 {
		mods = append(mods, qm.Select(columns...))
	}

	list, err = model.ProductTermMeta(mods...).All(ctx, r.mysqlConn)
	if withCount >= 2 {
		if limit > 0 && len(list) > limit {
			nextCount = 1
			list = list[:limit]
		}
		count = previousCount + nextCount*2
	}

	return
}

func (r *customCurrentProductTermRepository) GetMedia(
	ctx context.Context,
	cols model.M,
	withCount int,
	filter map[string]map[string][]any,
) (list []*model.ProductAttachmentRelationship, count int64, err error) {
	var page int
	var pageSize int
	var limit int
	var selectCol string
	var mods []qm.QueryMod
	var nextCount int64
	var previousCount int64
	for k, v := range cols {
		switch k {
		case "page":
			if val, ok := v.(uint64); ok && val > 1 {
				page = int(val)
			}
		case "pageSize":
			if val, ok := v.(uint64); ok && val > 0 {
				pageSize = int(val)
			}
		case "limit":
			if val, ok := v.(uint32); ok && val > 0 {
				limit = int(val)
			}
		case "offset":
			if withCount == 2 {
				if val, ok := v.(uint32); ok && val > 0 {
					mods = append(mods, qm.Offset(int(val)))
					previousCount = 1
				}
			}
		case "orderBy":
			if val, ok := v.(string); ok && len(val) > 0 {
				mods = append(mods, qm.OrderBy(val))
			}
		case "preMinId":
			if withCount == 3 {
				if val, ok := v.(uint64); ok && val > 0 {
					mods = append(mods, qm.OrderBy(model.ProductAttachmentRelationshipColumns.AttachmentRelationshipID+" DESC"))
					mods = append(mods, model.ProductAttachmentRelationshipWhere.AttachmentRelationshipID.LT(val))
					previousCount = 1
				}
			}
		case "preMaxId":
			if withCount == 4 {
				if val, ok := v.(uint64); ok && val > 0 {
					mods = append(mods, qm.OrderBy(model.ProductAttachmentRelationshipColumns.AttachmentRelationshipID+" ASC"))
					mods = append(mods, model.ProductAttachmentRelationshipWhere.AttachmentRelationshipID.GT(val))
					previousCount = 1
				}
			}
		case "select":
			if val, ok := v.(string); ok && len(val) > 0 {
				selectCol = val
			}
		}
	}

	for key, opMap := range filter {
		switch key {
		case model.ProductAttachmentRelationshipColumns.AttachmentRelationshipID:
			mods = append(mods, modelx.GetIntMods(model.ProductAttachmentRelationshipColumns.AttachmentRelationshipID, opMap)...)
		case model.ProductAttachmentRelationshipColumns.ObjectID:
			mods = append(mods, modelx.GetIntMods(model.ProductAttachmentRelationshipColumns.ObjectID, opMap)...)
		case model.ProductAttachmentRelationshipColumns.ObjectType:
			mods = append(mods, modelx.GetIntMods(model.ProductAttachmentRelationshipColumns.ObjectType, opMap)...)
		case model.ProductAttachmentRelationshipColumns.AttachmentID:
			mods = append(mods, modelx.GetIntMods(model.ProductAttachmentRelationshipColumns.AttachmentID, opMap)...)
		case model.ProductAttachmentRelationshipColumns.AttachmentThumbnail:
			mods = append(mods, modelx.GetIntMods(model.ProductAttachmentRelationshipColumns.AttachmentThumbnail, opMap)...)
		case model.ProductAttachmentRelationshipColumns.AttachmentOrder:
			mods = append(mods, modelx.GetIntMods(model.ProductAttachmentRelationshipColumns.AttachmentOrder, opMap)...)
		case model.ProductAttachmentRelationshipColumns.AttachmentSource:
			mods = append(mods, modelx.GetStringMods(model.ProductAttachmentRelationshipColumns.AttachmentSource, opMap)...)
		case model.ProductAttachmentRelationshipColumns.AttachmentImageURL:
			mods = append(mods, modelx.GetStringMods(model.ProductAttachmentRelationshipColumns.AttachmentImageURL, opMap)...)
		}
	}

	if withCount >= 2 {
		if limit > 0 {
			mods = append(mods, qm.Limit(limit+1))
		}
	} else if withCount >= 0 {
		count, err = model.ProductAttachmentRelationships(mods...).Count(ctx, r.mysqlConn)
		if err != nil {
			return
		}

		if withCount == 0 {
			return
		}

		if pageSize > 0 {
			if page > 1 {
				mods = append(mods, qm.Offset(pageSize*(page-1)))
			}
			mods = append(mods, qm.Limit(pageSize))
		}
	} else {
		if pageSize > 0 {
			if page > 1 {
				mods = append(mods, qm.Offset(pageSize*(page-1)))
			}
			mods = append(mods, qm.Limit(pageSize))
		}
	}

	var columns []string
	if selectCol != "" {
		if selectCol != "," {
			columns = strings.Split(selectCol, ",")
		} else {
			columns = append(columns, model.ProductAttachmentRelationshipColumns.AttachmentRelationshipID)
		}
	}
	if len(columns) > 0 {
		mods = append(mods, qm.Select(columns...))
	}

	list, err = model.ProductAttachmentRelationships(mods...).All(ctx, r.mysqlConn)
	if withCount >= 2 {
		if limit > 0 && len(list) > limit {
			nextCount = 1
			list = list[:limit]
		}
		count = previousCount + nextCount*2
	}

	return
}

func (r *customCurrentProductTermRepository) GetRelationshipList(
	ctx context.Context,
	cols model.M,
	withCount int,
	filter map[string]map[string][]any,
) (list []*model.ProductTermRelationship, count int64, err error) {
	var page int
	var pageSize int
	var limit int
	var selectCol string
	var mods []qm.QueryMod
	var nextCount int64
	var previousCount int64
	var random bool
	for k, v := range cols {
		switch k {
		case "page":
			if val, ok := v.(uint64); ok && val > 1 {
				page = int(val)
			}
		case "pageSize":
			if val, ok := v.(uint64); ok && val > 0 {
				pageSize = int(val)
			}
		case "limit":
			if val, ok := v.(uint32); ok && val > 0 {
				limit = int(val)
			}
		case "offset":
			if withCount == 2 {
				if val, ok := v.(uint32); ok && val > 0 {
					mods = append(mods, qm.Offset(int(val)))
					previousCount = 1
				}
			}
		case "orderBy":
			if val, ok := v.(string); ok && len(val) > 0 {
				mods = append(mods, qm.OrderBy(val))
			}
		case "preMinId":
			if withCount == 3 {
				if val, ok := v.(uint64); ok && val > 0 {
					mods = append(mods, qm.OrderBy(model.ProductTermRelationshipColumns.TermRelationshipID+" DESC"))
					mods = append(mods, model.ProductTermRelationshipWhere.TermRelationshipID.LT(val))
					previousCount = 1
				}
			}
		case "preMaxId":
			if withCount == 4 {
				if val, ok := v.(uint64); ok && val > 0 {
					mods = append(mods, qm.OrderBy(model.ProductTermRelationshipColumns.TermRelationshipID+" ASC"))
					mods = append(mods, model.ProductTermRelationshipWhere.TermRelationshipID.GT(val))
					previousCount = 1
				}
			}
		case "select":
			if withCount != 5 {
				if val, ok := v.(string); ok && len(val) > 0 {
					selectCol = val
				}
			}
		case "random":
			if val, ok := v.(string); ok && val == "1" {
				random = true
			}
		}
	}

	for key, opMap := range filter {
		switch key {
		case model.ProductTermRelationshipColumns.TermRelationshipID:
			mods = append(mods, modelx.GetIntMods(model.ProductTermRelationshipColumns.TermRelationshipID, opMap)...)
		case model.ProductTermRelationshipColumns.ObjectID:
			mods = append(mods, modelx.GetIntMods(model.ProductTermRelationshipColumns.ObjectID, opMap)...)
		case model.ProductTermRelationshipColumns.ObjectType:
			mods = append(mods, modelx.GetIntMods(model.ProductTermRelationshipColumns.ObjectType, opMap)...)
		case model.ProductTermRelationshipColumns.TermID:
			mods = append(mods, modelx.GetIntMods(model.ProductTermRelationshipColumns.TermID, opMap)...)
		case model.ProductTermRelationshipColumns.TermOrder:
			mods = append(mods, modelx.GetIntMods(model.ProductTermRelationshipColumns.TermOrder, opMap)...)
		}
	}

	if random {
		subMods := make([]qm.QueryMod, len(mods), len(mods)+2)
		copy(subMods, mods)
		subMods = append(subMods, qm.Select(fmt.Sprintf(
			"max(%s) as max_id, min(%s) as min_id, RAND() as rand",
			model.ProductTermRelationshipColumns.ObjectID,
			model.ProductTermRelationshipColumns.ObjectID,
		)))
		subMods = append(subMods, qm.From(model.TableNames.ProductTermRelationships))

		var info RandomInfo
		// Use query building
		err = model.NewQuery(subMods...).Bind(ctx, r.mysqlConn, &info)
		if err != nil {
			return
		}

		rand := int(float64(info.MaxId-info.MinId)*info.Rand) + info.MinId
		mods = append(mods, model.ProductTermRelationshipWhere.ObjectID.GTE(uint64(rand)))
		mods = append(mods, qm.Distinct(model.ProductTermRelationshipColumns.ObjectID))

		if pageSize > 0 {
			mods = append(mods, qm.Limit(pageSize))
		}

		var columns []string
		if len(selectCol) > 0 {
			if selectCol == "," {
				columns = append(columns, model.ProductTermRelationshipColumns.ObjectID)
				columns = append(columns, model.ProductTermRelationshipColumns.TermID)
			} else {
				columns = strings.Split(selectCol, ",")
			}
		}
		if len(columns) > 0 {
			mods = append(mods, qm.Select(columns...))
		}

		list, err = model.ProductTermRelationships(mods...).All(ctx, r.mysqlConn)
		return
	}

	if withCount >= 2 {
		if limit > 0 {
			mods = append(mods, qm.Limit(limit+1))
		}
	} else if withCount >= 0 {
		count, err = model.ProductTermRelationships(mods...).Count(ctx, r.mysqlConn)
		if err != nil {
			return
		}

		if withCount == 0 {
			return
		}
	}

	if pageSize > 0 && (withCount == -1 || withCount == 1) {
		if page > 1 {
			mods = append(mods, qm.Offset(pageSize*(page-1)))
		}
		mods = append(mods, qm.Limit(pageSize))
	}

	var columns []string
	if len(selectCol) > 0 {
		if selectCol == "," {
			columns = append(columns, model.ProductTermRelationshipColumns.ObjectID)
			columns = append(columns, model.ProductTermRelationshipColumns.TermID)
		} else {
			columns = strings.Split(selectCol, ",")
		}
	}
	if len(columns) > 0 {
		mods = append(mods, qm.Select(columns...))
	}

	list, err = model.ProductTermRelationships(mods...).All(ctx, r.mysqlConn)
	if err != nil {
		return
	}

	if withCount >= 2 {
		if limit > 0 && len(list) > limit {
			nextCount = 1
			list = list[:limit]
		}
		count = previousCount + nextCount*2
	}

	return
}
